# management/commands/delete_djchef.py
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from django.contrib.auth import get_user_model
from apps.chefs.models import (
    DjChef, DjChefVerification,  
    Dish, ChefReview
)
from apps.menu.models import DjDish, DjDishImage
from apps.payments.models import (DjChefWallet,
    DjChefBankCard, DjWithdrawal,DjWalletTransaction
)
from apps.orders.models import (
    DjChefOrder,
    DjChefOrderItem, DjChefOrderStatusLog, DjChefReview,
    Order,
    OrderItem,
    OrderStatusLog,
)
from apps.schedules.models import TimeSlot
User = get_user_model()

class Command(BaseCommand):
    help = '彻底删除指定DjChef用户及其所有关联数据（仅用于测试环境）'

    def add_arguments(self, parser):
        parser.add_argument('chef_id', type=int, help='要删除的DjChef ID')
        parser.add_argument(
            '--force',
            action='store_true',
            help='强制删除，不进行确认提示',
        )

    def handle(self, *args, **options):
        chef_id = options['chef_id']
        force = options['force']

        try:
            # 确保获取的是DjChef实例（关键修正点）
            dj_chef = DjChef.objects.select_related('user').get(id=chef_id)
        except DjChef.DoesNotExist:
            raise CommandError(f'DjChef with ID {chef_id} does not exist')

        # 显示警告信息
        self.stdout.write(self.style.WARNING(
            f'警告：即将彻底删除 DjChef (ID: {chef_id}, 用户名: {dj_chef.user.username if dj_chef.user else "未关联用户"}) 及其所有关联数据！'
        ))
        self.stdout.write(self.style.WARNING('此操作不可逆，仅应在测试环境中使用！'))

        if not force:
            confirm = input('是否继续？[y/N] ')
            if confirm.lower() != 'y':
                self.stdout.write(self.style.SUCCESS('操作已取消'))
                return

        try:
            with transaction.atomic():
                # 1. 删除订单相关数据（严格使用DjChef实例关联查询）
                orders = Order.objects.filter(chef=dj_chef)  # 确保用dj_chef实例查询
                order_ids = orders.values_list('id', flat=True)
                
                OrderStatusLog.objects.filter(order_id__in=order_ids).delete()
                OrderItem.objects.filter(order_id__in=order_ids).delete()
                
                chef_orders = DjChefOrder.objects.filter(chef=dj_chef)  # 直接通过chef关联删除
                chef_order_ids = chef_orders.values_list('id', flat=True)
                DjChefOrderStatusLog.objects.filter(order_id__in=chef_order_ids).delete()
                DjChefOrderItem.objects.filter(order_id__in=chef_order_ids).delete()
                chef_orders.delete()
                
                orders.delete()
                self.stdout.write(f'已删除关联的订单及相关记录')

                # 2. 删除时间档期
                TimeSlot.objects.filter(chef=dj_chef).delete()  # 确保用dj_chef实例
                self.stdout.write(f'已删除关联的时间档期记录')

                # 3. 钱包及金融相关数据
                try:
                    wallet = DjChefWallet.objects.get(chef=dj_chef)
                    DjChefBankCard.objects.filter(wallet=wallet).delete()
                    DjWithdrawal.objects.filter(wallet=wallet).delete()
                    wallet.delete()
                    self.stdout.write(f'已删除关联的钱包、银行卡及提现记录')
                except DjChefWallet.DoesNotExist:
                    self.stdout.write(f'未找到关联的钱包记录')

                # 4. 其他关联数据
                DjChefReview.objects.filter(chef=dj_chef).delete()
                self.stdout.write(f'已删除关联的厨师评价')

                chef_dishes = DjDish.objects.filter(chef=dj_chef)
                # 批量删除这些菜品关联的图片（通过两种关联关系确保删除干净）
                # 1) 通过 DjDishImage 的 dish 外键直接删除
                DjDishImage.objects.filter(dish__in=chef_dishes).delete()
                # 2) 通过 DjDish 的 dish_images 多对多关系删除（双重保险）
                for dish in chef_dishes:
                    dish.dish_images.clear()  # 清除多对多关联
                chef_dishes.delete()  # 最后删除菜品本身
                self.stdout.write(f'已删除关联的菜品及图片记录')

                DjDish.objects.filter(chef=dj_chef).delete()
                self.stdout.write(f'已删除关联的菜品记录')


                DjChefVerification.objects.filter(chef=dj_chef).delete()
                self.stdout.write(f'已删除关联的认证信息')

                
                try:
                    # 获取厨师关联的钱包
                    chef_wallet = DjChefWallet.objects.get(chef=dj_chef)
                    # 删除该钱包的所有交易流水
                    DjWalletTransaction.objects.filter(wallet=chef_wallet).delete()
                    self.stdout.write(f'已删除关联的钱包交易流水（通过钱包关联）')
                except DjChefWallet.DoesNotExist:
                    self.stdout.write(f'未找到该厨师的关联钱包，跳过钱包交易流水删除')

                # 2. 双重保险：通过 chef_id 字段直接删除（防止外键关联异常时的残留数据）
                DjWalletTransaction.objects.filter(chef_id=dj_chef.id).delete()
                self.stdout.write(f'已删除关联的钱包交易流水（通过chef_id字段）')

                # 5. 删除关联用户
                if dj_chef.user:
                    user = dj_chef.user
                    dj_chef.user = None
                    dj_chef.save(update_fields=['user'])
                    user.delete()
                    self.stdout.write(f'已删除关联的用户账号')

                # 6. 最后删除DjChef
                dj_chef.delete()
                self.stdout.write(self.style.SUCCESS(f'DjChef (ID: {chef_id}) 及其所有关联数据已成功删除'))

        except Exception as e:
            raise CommandError(f'删除过程中发生错误: {str(e)}')